package com.easemob.helpdesk.activity.history;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.easemob.helpdesk.AppConfig;
import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.bean.User;
import com.easemob.helpdesk.bean.UserInfo;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.DialogUtils;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.R;
//import com.easemob.helpdesk.activity.BaseActivity;
import com.easemob.helpdesk.activity.BaseActivityV2;
import com.easemob.helpdesk.activity.CategoryShowActivity;
//import com.easemob.helpdesk.activity.visitor.CustomerDetailActivity;
import com.easemob.helpdesk.adapter.ChatAdapter;
import com.easemob.helpdesk.activity.ChatActivity;
import com.easemob.helpdesk.recorder.MediaManager;
import com.easemob.helpdesk.widget.popupwindow.HistorySessionMore;
import com.hyphenate.kefusdk.HDDataCallBack;
//import com.hyphenate.kefusdk.bean.HDCategorySummary;
//import com.hyphenate.kefusdk.bean.HDSession;
//import com.hyphenate.kefusdk.bean.HistorySessionEntity;
import com.hyphenate.kefusdk.chat.HDClient;
import com.hyphenate.kefusdk.entity.HDCategorySummary;
import com.hyphenate.kefusdk.entity.HDMessage;
//import com.hyphenate.kefusdk.entity.HDUser;
//import com.hyphenate.kefusdk.entity.HDVisitorUser;
import com.hyphenate.kefusdk.entity.HDSession;
import com.hyphenate.kefusdk.entity.option.OptionEntity;
import com.hyphenate.kefusdk.entity.user.HDVisitorUser;
import com.hyphenate.kefusdk.manager.session.SessionManager;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;
import com.zdxd.tagview.Tag;
import com.zdxd.tagview.TagView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import retrofit2.Call;


/**
 * Created by lyuzhao on 2015/12/16.
 */
public class HistoryChatActivity extends BaseActivityV2  {

	private final String TAG = getClass().getSimpleName();

	private static final int REQUEST_CODE_CATEGORY_SHOW = 0x01;



	protected Button btnCallback;

	protected RecyclerView mRecyclerView;

	protected LinearLayout llChannel;

	protected ImageView iv_channel;

	protected TextView tvChannelText;

	protected TextView tvTitle;

	ImageView vipIcon;

//	@BindView(R.id.btn_up)
//	protected ImageButton btnUp;
//
//	@BindView(R.id.btn_down)
//	protected ImageButton btnDown;
//
//	@BindView(R.id.tag_layout)
//	protected LinearLayout tagLayout;
//
//	@BindView(R.id.tagview)
//	protected TagView tagGroup;
//
//	@BindView(R.id.tv_note)
//	protected TextView tvNote;

	@Override
	protected void initFindView() {
		super.initFindView();

		btnCallback=findViewById(R.id.btn_call_back);
		mRecyclerView=findViewById(R.id.history_listview);
		llChannel=findViewById(R.id.ll_channel);
		iv_channel=findViewById(R.id.iv_channel);
		tvChannelText=findViewById(R.id.tv_channel_content);

		tvTitle=findViewById(R.id.user_name);
		vipIcon=findViewById(R.id.vip_icon);

		llTitleClick=findViewById(R.id.ll_title_click);
		ibMenuMore=findViewById(R.id.ib_menu_more);
		swipeRefreshLayout=findViewById(R.id.chat_swipe_layout);
		tvTitle=findViewById(R.id.user_name);
		tvTitle=findViewById(R.id.user_name);

		View rl_back=findViewById(R.id.rl_back);
		rl_back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				finish();
			}
		});

		btnCallback.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (pd == null) {
					pd = DialogUtils.getLoadingDialog(HistoryChatActivity.this, "正在再次发起会话...");
				}
//				pd.setMessage("正在再次发起会话...");
				pd.show();
				sessionManager.asyncCreateSession(new HDDataCallBack<HDSession>() {
					@Override
					public void onSuccess(final HDSession sessionEntty) {
						if (isFinishing()) {
							return;
						}
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								closeDialog();
								Toast.makeText(getApplicationContext(), "再次发起会话成功！", Toast.LENGTH_SHORT).show();
								Intent intent = new Intent();
								intent.setClass(HistoryChatActivity.this, ChatActivity.class);
								intent.putExtra("visitorid", sessionEntty.getServiceSessionId());
								intent.putExtra("originType", originType);
								intent.putExtra("user", sessionEntty.getUser());
								intent.putExtra("chatGroupId", sessionEntty.getChatGroupId());
								intent.putExtra("techChannelName", techChannelName);

								intent.putExtra("truename", truename);
								intent.putExtra("user_phone",  user_phone);
								intent.putExtra("username", username);
								intent.putExtra("addr", addr);

								startActivity(intent);
								finish();
							}
						});
					}

					@Override
					public void onError(final int error, String errorMsg) {
						if (isFinishing()) {
							return;
						}
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								closeDialog();
								if (error == 400) {
									Toast.makeText(getApplicationContext(), "再次发起会话失败，该访客有尚未结束的会话！", Toast.LENGTH_SHORT).show();
								} else {
									Toast.makeText(getApplicationContext(), "再次发起会话失败！", Toast.LENGTH_SHORT).show();
								}
							}
						});
					}
				});
			}
		});

	}
	protected LinearLayout llTitleClick;
	protected ImageButton ibMenuMore;

	/**
	 * 加载更多的View
	 */
	public SwipeRefreshLayout swipeRefreshLayout;

	/**
	 * 是否有更多的数据
	 */
	private boolean haveMoreData = true;
	/**
	 * 当前是否正在加载数据
	 */
	private boolean isLoadding = false;

	private String originType;
	private String techChannelName;

	private String truename;
	private String user_phone;
	private String username;
	private String addr;

	public ChatAdapter mAdapter;

	private Dialog pd = null;
	private HDVisitorUser visitorUser;
	private String sessionId = null;
	private String commentString;

	private SessionManager sessionManager;
	private boolean isWait;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppConfig.setFitWindowMode(this);
		setContentView(R.layout.activity_history_chat);
		initFindView();
		Intent intent = getIntent();
		sessionId = intent.getStringExtra("visitorid");
		visitorUser = intent.getParcelableExtra("user");
		originType = intent.getStringExtra("originType");
		techChannelName = intent.getStringExtra("techChannelName");
		isWait = intent.getBooleanExtra("isWait",false);
		long chatGroupId = intent.getLongExtra("chatGroupId", 0);
		sessionManager = new SessionManager(chatGroupId, sessionId, visitorUser, null);
		initDatas();
		initListener();
		LoadRemoteMsg();
		//获取tagsView
//		getTagsFromRemote();
//		getCommentsFromRemote();

		if (!isWait) {
			//获取tagsView
			getTagsFromRemote();
			getCommentsFromRemote();
//			getSessionExtraInfo();
		} else {
//			sessionExtraInfo.setVisibility(View.GONE);
			btnCallback.setText("-> 接入");
			ibMenuMore.setVisibility(View.GONE);
//			tagContainer.setVisibility(View.GONE);
		}

//		getSessionExtraInfo();
//		new Handler().postDelayed(new Runnable() {
//			@Override
//			public void run() {
//				tagLayout.setVisibility(View.GONE);
//			}
//		}, 300);
	}

	private void initListener() {
//		llTitleClick.setOnClickListener(this);
//		btnUp.setOnClickListener(this);
//		btnDown.setOnClickListener(this);
//		btnCallback.setOnClickListener(this);
	}

//	@OnClick(R.id.rl_back)
//	public void onClickByBack(){
//		finish();
//	}

	private void getTagsFromRemote() {
		sessionManager.getCategorySummarys(new HDDataCallBack<List<HDCategorySummary>>() {
			@Override
			public void onSuccess(final List<HDCategorySummary> value) {
				if (isFinishing()) {
					return;
				}
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						setTagViews(value);
					}
				});
			}

			@Override
			public void onError(int error, String errorMsg) {

			}
		});
	}

	private void setTagViews(List<HDCategorySummary> list) {

		Tag tag;
//		if (list == null || list.size() == 0) {
//			tagGroup.addTags(new ArrayList<Tag>());
//			return;
//		}
//		ArrayList<Tag> tags = new ArrayList<>();
//		for (int i = 0; i < list.size(); i++) {
//			HDCategorySummary entty = list.get(i);
//			String rootName = (TextUtils.isEmpty(entty.rootName)) ? "" : entty.rootName + ">";
//			tag = new Tag(rootName + entty.name);
//			tag.id = entty.id;
//			tag.radius = 10f;
//			int color = (int) entty.color;
//			String strColor;
//			if (color == 0) {
//				strColor = "#000000";
//			} else if (color == 255) {
//				strColor = "#ffffff";
//			} else {
//				strColor = "#" + Integer.toHexString(color);
//				strColor = strColor.substring(0, 7);
//			}
//			tag.layoutColor = Color.parseColor(strColor);
//			tag.isDeletable = false;
//			tags.add(tag);
//
//		}
//		tagGroup.addTags(tags);
	}


	private void getCommentsFromRemote() {
		sessionManager.getCommentsFromServer(new HDDataCallBack<String>() {
			@Override
			public void onSuccess(final String value) {
				if (isFinishing()) {
					return;
				}
				commentString = value;
//				runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						if (TextUtils.isEmpty(value)){
//							tvNote.setText("");
//						}else{
//							tvNote.setText("备注：" + value);
//						}
//					}
//				});
			}

			@Override
			public void onError(int error, String errorMsg) {

			}
		});
	}


	private void getUserInfo(final HDVisitorUser visitorUser) {
//		OkHttpClient okHttpClient = new OkHttpClient();
		final String val = visitorUser.getUsername();

		if(!TextUtils.isEmpty(val) && val.contains("#")){
			String uid = val.split("#")[0];

			ApiService apiService = HKHttpUtils.getApiService();
			Call<BaseResponse<User>> call = apiService.getUserById(MainActivity.ticket,String.valueOf(uid));
			call.enqueue(new HKResponseResultCallBack<User>() {
				@Override
				public void onSuccess(User user) {
					if (user != null){
						if(!TextUtils.isEmpty(user.getName())){
							tvTitle.setText(user.getName());
						}else{
							tvTitle.setText(visitorUser.getNicename());
						}

						truename = user.getName();
						user_phone = user.getPhone();
						username = val;
						addr = user.getHomeAddress();

						if (user.getIsVip() == 1){
							vipIcon.setVisibility(View.VISIBLE);
						}else {
							vipIcon.setVisibility(View.GONE);
						}
					}
				}

				@Override
				public void onGetDataFailed(int cd, String msg) {
					Toast.makeText(HistoryChatActivity.this, "请求失败:"+msg, Toast.LENGTH_SHORT).show();
				}

				@Override
				public void onFailed(Call call, Throwable t) {
					Toast.makeText(HistoryChatActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
				}
			});

//			RequestBody body = new FormBody.Builder()
//					.add("uid", String.valueOf(uid))
//					.build();
//
//			Request request = new Request.Builder()
//					.url(BuildConfig.API_URL + "account/findUserById")
//					.post(body)
//					.build();
//
//			Call call = okHttpClient.newCall(request);
//
//			call.enqueue(new Callback() {
//				@Override
//				public void onFailure(Call call, IOException e) {
//					e.printStackTrace();
//					runOnUiThread(new Runnable() {
//						@Override
//						public void run() {
//							Toast.makeText(HistoryChatActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
//						}
//					});
//				}
//
//				@Override
//				public void onResponse(Call call, Response response) throws IOException {
//
//					final String res = response.body().string();
//					final UserInfo result = CommonUtils.parseJsonWithGson(res, UserInfo.class);
//
//					runOnUiThread(new Runnable() {
//						@Override
//						public void run() {
//							if(result.getData() != null){
//
//								if(!TextUtils.isEmpty(result.getData().getName())){
//									userName.setText(result.getData().getName());
//								}else{
//									userName.setText(visitorUser.getNicename());
//								}
//
//								truename = result.getData().getName();
//								user_phone = result.getData().getPhone();
//								username = val;
//								addr = result.getData().getHomeAddress();
//							}
//						}
//					});
//
//				}
//			});

		}

	}


	private void initDatas() {
		if (pd == null) {
			pd = DialogUtils.getLoadingDialog(this, getResources().getString(R.string.loading_getdata));
//			pd.setMessage(getResources().getString(R.string.loading_getdata));
		}
		pd.show();
		final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
		mRecyclerView.setLayoutManager(layoutManager);

//		if (visitorUser != null && !TextUtils.isEmpty(visitorUser.getNicename())) {
//			userName.setText(visitorUser.getNicename());
//		}

		getUserInfo(visitorUser);

		mAdapter = new ChatAdapter(this, sessionManager, mRecyclerView, visitorUser.getUsername());
		mRecyclerView.setAdapter(mAdapter);

//		llChannel.setVisibility(View.VISIBLE);
//		if (!TextUtils.isEmpty(originType)) {
//			switch (originType) {
//				case "weibo":
//					iv_channel.setImageResource(R.drawable.channel_weibo_icon);
//					break;
//				case "weixin":
//					iv_channel.setImageResource(R.drawable.channel_wechat_icon);
//					break;
//				case "webim":
//					iv_channel.setImageResource(R.drawable.channel_web_icon);
//					break;
//				case "app":
//					iv_channel.setImageResource(R.drawable.channel_app_icon);
//					break;
//			}
//			if (!TextUtils.isEmpty(techChannelName)) {
//				tvChannelText.setText("会话来自:" + techChannelName);
//			}
//		}


		swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_dark,
				R.color.holo_orange_light, R.color.holo_red_light);
		swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh() {
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						int firstVisibilePosition = layoutManager.findFirstVisibleItemPosition();
						if (firstVisibilePosition == 0 && !isLoadding && haveMoreData) {
							sessionManager.asyncGetSessionMessages(new HDDataCallBack<List<HDMessage>>() {
								@Override
								public void onSuccess(final List<HDMessage> value) {
									swipeRefreshLayout.setRefreshing(false);
									isLoadding = false;
									runOnUiThread(new Runnable() {
										@Override
										public void run() {
											if (value.isEmpty()){
												haveMoreData = false;
												Toast.makeText(mActivity, getString(R.string.txt_no_more_message), Toast.LENGTH_SHORT).show();
												return;
											}else{
												mAdapter.refresh();
											}
										}
									});
								}

								@Override
								public void onError(int error, String errorMsg) {
									if (isFinishing()) {
										return;
									}
									runOnUiThread(new Runnable() {
										@Override
										public void run() {
											isLoadding = false;
											swipeRefreshLayout.setRefreshing(false);
										}
									});

								}
							});
						} else {
							Toast.makeText(mActivity, getString(R.string.txt_no_more_message), Toast.LENGTH_SHORT).show();
						}
						if (swipeRefreshLayout != null){
							swipeRefreshLayout.setRefreshing(false);
						}


					}
				}, 1000);
			}
		});


	}


	private void LoadRemoteMsg() {
		sessionManager.asyncGetSessionMessages(new HDDataCallBack<List<HDMessage>>() {
			@Override
			public void onSuccess(List<HDMessage> value) {
				if (isFinishing()) {
					return;
				}
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						closeDialog();
						mAdapter.refresh();
					}
				});
			}

			@Override
			public void onError(int error, String errorMsg) {
				if (isFinishing()) {
					return;
				}
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						closeDialog();
						Toast.makeText(mActivity, "网络请求失败！", Toast.LENGTH_SHORT).show();
					}
				});
			}
		});
	}

	public RecyclerView getListView() {
		return mRecyclerView;
	}

	private void closeDialog(){
		if (pd != null) {
			pd.dismiss();
		}
	}

/*	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.ll_title_click: {
//				if (TextUtils.isEmpty(sessionId)) {
//					return;
//				}
//				HDUser emUser = HDClient.getInstance().getCurrentUser();
//				if (emUser == null){
//					return;
//				}
//				Intent intent = new Intent();
//				intent.putExtra("visitorId", sessionId);
//				intent.putExtra("userId", visitorUser.getUserId());
//				intent.putExtra("tenantId", emUser.getTenantId());
//				intent.setClass(mActivity, CustomerDetailActivity.class);
//				startActivity(intent);
			}
			break;
			case R.id.btn_call_back:


				break;
//			case R.id.btn_up:
//				tagLayout.setVisibility(View.GONE);
//				btnUp.setVisibility(View.INVISIBLE);
//				btnDown.setVisibility(View.VISIBLE);
//				break;
//			case R.id.btn_down:
//				tagLayout.setVisibility(View.VISIBLE);
//				btnUp.setVisibility(View.VISIBLE);
//				btnDown.setVisibility(View.INVISIBLE);
//				break;
			default:
				break;
		}
	}*/

	HistorySessionMore sessionMoreWindow;

	public void sessionMore(View view) {
		if (sessionMoreWindow == null) {
			sessionMoreWindow = new HistorySessionMore(this);
		}
		sessionMoreWindow.showPopupWindow(ibMenuMore);
	}


	public void lable_setting(View view) {
		popupclose(null);
		startActivityForResult(new Intent(this, CategoryShowActivity.class).putExtra("sessionId", sessionId).putExtra("value", sessionManager.getCategoryTreeValue()), REQUEST_CODE_CATEGORY_SHOW);
//
	}

	public void popupclose(View view) {
		if (sessionMoreWindow != null && sessionMoreWindow.isShowing()) {
			sessionMoreWindow.dismiss();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == REQUEST_CODE_CATEGORY_SHOW) {
				String newValue = data.getStringExtra("value");
				String comment = data.getStringExtra("comment");
				if (!newValue.equals(sessionManager.getCategoryTreeValue())) {
					getTagsFromRemote();
				}
				if (commentString == null) {
					commentString = "";
				}
				if (comment == null) {
					comment = "";
				}
				if (!commentString.equals(comment)) {
					getCommentsFromRemote();
				}
			}
		}


	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		MediaManager.release();
	}

//	private void getSessionExtraInfo() {
//		OptionEntity optionEntity = HDClient.getInstance().agentManager().getOptionEntity("sessionOpenNoticeEnable");
//
//		if (optionEntity != null && optionEntity.getOptionValue().equals("true")) {
//			sessionManager.getSessionExtraInfo(new HDDataCallBack<String>() {
//				@Override
//				public void onSuccess(final String value) {
//					runOnUiThread(new Runnable() {
//						@Override
//						public void run() {
//							if (sessionExtraInfo != null) {
////								sessionExtraInfo.setText(value);
//							}
//						}
//					});
//				}
//
//				@Override
//				public void onError(int error, String errorMsg) {
//
//				}
//			});
//		}
//	}
}
